package com.zhonglz.support.listener;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.zhonglz.model.BuCertInfo;
import com.zhonglz.model.SysFileInfo;
import com.zhonglz.service.BuCertInfoService;
import com.zhonglz.service.SysFileInfoService;
import com.zhonglz.support.event.SealSignDataEvent;
import com.zhonglz.support.model.SealSignData;
import com.zhonglz.util.cert.sm2.CertificateUtils;
import com.zhonglz.util.file.FileUtils;
import com.zhonglz.util.minio.MinioUtils;
import com.zhonglz.util.sign.pdf.rsa.SignRSAPdf;
import com.zhonglz.util.tools.ObjectUtils;


/**
 * 证书签名验证监听
 * @author zhonglz
 *
 */
@Component
public class CertSignListener {

	private static Logger logger = LoggerFactory.getLogger(CertSignListener.class);
	
	@Autowired
	private BuCertInfoService buCertInfoService;
	
	@Autowired
	private SysFileInfoService sysFileInfoService;
	
	@Order(10)
    @EventListener
    public void acceptEvent(SealSignDataEvent event) {
		logger.info("***************证书签名验证监听开始********************");
		SealSignData sealSignData =event.getSealSignData();
		BuCertInfo buCertInfo= buCertInfoService.selectById(sealSignData.getBuSignInfo().getCertId());
		if(!sealSignData.getCertPwd().equals(buCertInfo.getCertPwd())) {
			throw new RuntimeException("证书密码输入错误");
		}
		SysFileInfo sysFileInfo =sysFileInfoService.selectByPrimaryKey(buCertInfo.getCertUrl());
		if(ObjectUtils.isEmpty(sysFileInfo)) {
			throw new RuntimeException("证书文件信息获取失败");
		}
		try {
			sealSignData.setCertFile(MinioUtils.getObjectBytes(sysFileInfo.getFileAddress()));
			if(buCertInfo.getCertType().equals("rsa")) {
				/// 国际rsa证书
				InputStream input = MinioUtils.getObject(sysFileInfo.getFileAddress());
				KeyStore ks = KeyStore.getInstance("JKS");
		        // jks文件密码，根据实际情况修改
		        ks.load(input, buCertInfo.getCertPwd().toCharArray());
		        String alias = (String) ks.aliases().nextElement();
		        PrivateKey pk = (PrivateKey) ks.getKey(alias,buCertInfo.getCertPwd().toCharArray());
		        Certificate[] chain = ks.getCertificateChain(alias);
		        sealSignData.setChain(chain);
		        sealSignData.setPrivateKey(pk);
			}else if(buCertInfo.getCertType().equals("sm2")) {
				/// 国密sm2证书
				byte[] filebyte = MinioUtils.getObjectBytes(sysFileInfo.getFileAddress());
				X509Certificate x509Certificate = CertificateUtils.getX509CertificateFromPfx(filebyte, buCertInfo.getCertPwd());
				BCECPrivateKey pk = CertificateUtils.getBCECPrivateKeyFromPfx(filebyte, buCertInfo.getCertPwd());
				Certificate[] chain =new Certificate[]{x509Certificate};
			    sealSignData.setChain(chain);
			    sealSignData.setPrivateKey(pk);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("证书文件获取失败");
		}
		event.setSealSignData(sealSignData);
		logger.info("***************证书签名验证监听结束********************");
	}
}
